#!/usr/bin/env bash

stat () {
  local CLUSTER=$1
  local DAY=$2
  local HOUR=$3
  local FILE_PATTERN="$DAY-$HOUR"

  cd /mnt/logs/apigw/"$CLUSTER" || exit
  echo "entering dir $(pwd)"
  echo

  local FILE_NAMES=($(ls -l | grep "$FILE_PATTERN" | awk '{ print $NF }'))
  echo "find files matching $FILE_PATTERN"

  for i in "${FILE_NAMES[@]}"; do
    echo "$i"
  done
  echo

  echo "Now begin processing"
  local RESULT_FILE="/tmp/$FILE_PATTERN"
  echo "results file is $RESULT_FILE"
  echo
  for i in "${FILE_NAMES[@]}"; do
    zgrep -Eo ' "[[:digit:]]+" ' "$i" | grep -Eo '[[:digit:]]+' >> "$RESULT_FILE"
    echo "    process $i done!"
  done
  echo "grep done!"
  echo

  local NL=$(wc -l "$RESULT_FILE")
  echo "number of lines is $NL"
  echo

  echo "Now begin sort and count by tenent_id"
  local FREQ_FILE='/tmp/freq.log'
  sort -n $RESULT_FILE | uniq -c | sort -nr > "$FREQ_FILE"
  echo "Done, please check $FREQ_FILE"
}

stat $1 $2 $3
